package com.quectel.core.module.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.merchant.dao.MerchantVillageDao;
import com.quectel.core.module.merchant.dto.MerchantDto;
import com.quectel.core.module.merchant.dto.MerchantVillageDto;
import com.quectel.core.module.merchant.entity.MerchantVillageEntity;
import com.quectel.core.module.merchant.service.MerchantService;
import com.quectel.core.module.merchant.service.MerchantVillageService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/03/28 13:09
 */
@DubboService
public class MerchantVillageServiceImpl extends ServiceImpl<MerchantVillageDao, MerchantVillageEntity> implements MerchantVillageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MerchantVillageService.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> MERCHANT_VILLAGE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "MERCHANT_VILLAGE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<MerchantVillageDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(MERCHANT_VILLAGE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private MerchantVillageDao merchantVillageDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private MerchantService merchantService;


    @Override
    public List<MerchantVillageDto> selectByVillageId(Long villageId) {
        List<MerchantVillageEntity> merchantVillageEntities = merchantVillageDao.selectList(new LambdaQueryWrapper<MerchantVillageEntity>()
                .eq(MerchantVillageEntity::getVillageId, villageId));

        List<MerchantVillageDto> merchantVillageDtos = CopyUtils.copyList(merchantVillageEntities, MerchantVillageDto.class);
        merchantVillageDtos.forEach(this::paddingField);
        return merchantVillageDtos;
    }

    @Override
    @Transactional
    public void updateConfig(Long villageId, List<MerchantVillageDto> list) {
        if (list == null) {
            list = Lists.newArrayList();
        }
        VillageDto villageDto = villageService.selectCacheById(villageId);
        Preconditions.checkNotNull(villageDto);

        Long[] ids = selectByVillageId(villageId).parallelStream()
                .map(MerchantVillageDto::getId).toArray(Long[]::new);
        deleteBatch(ids);

        List<MerchantVillageEntity> merchantVillageEntities = CopyUtils.copyList(list, MerchantVillageEntity.class);
        for (MerchantVillageEntity merchantVillageEntity : merchantVillageEntities) {
            merchantVillageEntity.setId(Snowflake.nextId());
            merchantVillageEntity.setVillageId(villageDto.getId());
            merchantVillageEntity.setTenantId(villageDto.getTenantId());
        }
        super.saveBatch(merchantVillageEntities);
    }

    public MerchantVillageDto queryByVillageAndBusiness(Long villageId, String businessType) {
        MerchantVillageEntity entity = merchantVillageDao.selectOne(new LambdaQueryWrapper<MerchantVillageEntity>()
                .eq(MerchantVillageEntity::getVillageId, villageId)
                .eq(MerchantVillageEntity::getBusinessType, businessType)
        );
        return CopyUtils.copyObj(entity, MerchantVillageDto.class);
    }

    @Override
    public MerchantVillageDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                MERCHANT_VILLAGE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public MerchantVillageDto selectById(Long id) {
        MerchantVillageEntity entity = merchantVillageDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, MerchantVillageDto.class));
    }

    @Override
    public List<MerchantVillageDto> queryList(Map<String, Object> params) {
        List<MerchantVillageEntity> list = merchantVillageDao.queryList(params);
        List<MerchantVillageDto> result = CopyUtils.copyList(list, MerchantVillageDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private MerchantVillageDto paddingField(MerchantVillageDto dto) {
        if (dto != null) {
            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            dto.setVillage(villageDto);

            MerchantDto merchantDto = merchantService.selectCacheById(dto.getMerchantId());
            dto.setMerchant(merchantDto);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return merchantVillageDao.queryTotal(params);
    }

    @Override
    public Long save(MerchantVillageDto dto) {
        MerchantVillageEntity entity = CopyUtils.copyObj(dto, MerchantVillageEntity.class);
        entity.setId(Snowflake.nextId());
        merchantVillageDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(MerchantVillageDto dto) {
        MerchantVillageEntity entity = CopyUtils.copyObj(dto, MerchantVillageEntity.class);

        merchantVillageDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(MerchantVillageDto dto) {
        MerchantVillageEntity entity = CopyUtils.copyObj(dto, MerchantVillageEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, merchantVillageDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        merchantVillageDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
